<template>
  <div>
    <el-card class="box-card">
      <!-- 头部 -->
      <div slot="header" class="clearfix">
        <el-button
          type="primary"
          @click="showAddOrUpdate({ id: 0, tmName: '', logoUrl: '' })"
          ><i class="el-icon-plus"></i> 添加</el-button
        >
      </div>
      <!-- 表格 -->
      <el-table :data="TrademarkPageList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="80">
        </el-table-column>
        <el-table-column prop="tmName" label="品牌名称"> </el-table-column>
        <el-table-column label="品牌LOGO">
          <template v-slot="{ row }">
            <el-image :src="row.logoUrl" style="width: 100px;"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="warning" size="small" @click="showAddOrUpdate(row)"
              ><i class="el-icon-edit-outline"></i
            ></el-button>
            <el-button type="danger" size="small" @click="open(row.id)"
              ><i class="el-icon-delete"></i
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="sizechange"
        @current-change="currentchange"
        :current-page="current"
        :page-sizes="[3, 6, 9]"
        :page-size="limit"
        layout=" prev, pager, next, jumper, ->,sizes,total"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加和修改的Dialog -->
    <el-dialog
      :title="`${saveForm.id ? '修改' : '添加'}品牌`"
      :visible.sync="isDialogForm"
    >
      <el-form
        label-width="130px"
        :rules="rules"
        ref="ruleForm"
        :model="saveForm"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            v-model="saveForm.tmName"
            placeholder="请输入品牌名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="http://gmall-h5-api.atguigu.cn/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="saveForm.logoUrl"
              :src="saveForm.logoUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isDialogForm = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdate('ruleForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getTrademarkPageListApi,
  saveTrademarkApi,
  updateTrademarkApi,
  deleteTrademarkApi
} from "@/api/product/trademark.js";
export default {
  name: "Trademark",
  data() {
    return {
      /* 分页数据 */
      current: 1,
      pages: 5,
      limit: 3,
      total: 0,
      TrademarkPageList: [],

      /* 添加和修改的Dialog显示的标识 */
      isDialogForm: false,

      /* upload显示图片的标识 */
      isUploadImage: false,

      /* upload图片显示的路径 */

      /* 收集表单数据的对象 */
      saveForm: {
        tmName: "",
        logoUrl: ""
      },

      // 表单校验的数据
      rules: {
        tmName: [
          {
            required: true,
            message: "请输入品牌名称!",
            trigger: "blur"
          },
          {
            min: 3,
            max: 5,
            message: "长度在3-5个字符!",
            trigger: "blur"
          }
        ],
        logoUrl: [
          {
            required: true,
            message: "请选择品牌LOGO!",
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    // 表单校验
    submitForm(formName) {},
    resetForm(formName) {},
    // 删除品牌
    open(id) {
      this.$confirm("确定要删除此品牌吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await deleteTrademarkApi(id);
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.getTrademarkList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
          this.getTrademarkList();
        });
    },

    // 判断是添加还是修改
    showAddOrUpdate(tm) {
      // 清除/重置form中的数据
      this.saveForm.id = tm.id;
      this.saveForm.tmName = tm.tmName;
      this.saveForm.logoUrl = tm.logoUrl;

      // 显示dialog
      this.isDialogForm = true;
    },

    async addOrUpdate() {
      console.log(this.saveForm);
      // this.$refs.formRef.validate(valid => {
      //   // if (valid) {
      //   // } else {
      //   //   return false;
      //   // }
      // });

      let result;
      if (this.saveForm.id) {
        result = await updateTrademarkApi(this.saveForm);
        this.$message({
          message: "修改成功!",
          type: "success"
        });
      } else {
        result = await saveTrademarkApi(this.saveForm);
        this.$message({
          message: "添加成功!",
          type: "success"
        });
      }
      this.getTrademarkList();
      // 关闭Dialog
      this.isDialogForm = false;
    },
    // upload组件上传图片触发的函数
    handleAvatarSuccess(res, file) {
      // 路径重新赋值
      this.saveForm.logoUrl = res.data;
      console.log(res.data, "===");
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt50KB = file.size / 1024 < 50;

      if (!isJPG && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG 或 PNG 格式!");
      }
      if (!isLt50KB) {
        this.$message.error("上传头像图片大小不能超过 50KB!");
      }
      return (isLt50KB && isPNG) || isJPG;
    },
    // 当每页条数发生改变的时候触发的函数
    sizechange(val) {
      // 重新赋值
      this.limit = val;
      // 重新获取数据
      this.getTrademarkList();
    },
    // 当前页码发生改变的时候触发的函数
    currentchange(val) {
      // 重新赋值
      this.current = val;
      // 重新获取数据
      this.getTrademarkList();
    },

    // 获取分页列表数据
    async getTrademarkList() {
      // 发送请求
      const result = await getTrademarkPageListApi(this.current, this.limit);
      // console.log(result);
      // console.log(this.TrademarkPageList);

      //重新赋值
      this.TrademarkPageList = result.data.records;
      this.total = result.data.total;
      this.current = result.data.current;
      this.pages = result.data.pages;
    }
  },
  // 初始化
  mounted() {
    this.getTrademarkList();
  }
};
</script>
<style>
.el-dialog {
  height: 500px;
}
.dialog-footer {
  margin-top: 30px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
